﻿using UnityEngine;

public class Singleton<T> : MonoBehaviour
        where T : Component
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType(typeof(T)) as T;
                if (_instance == null)
                {
#if UNITY_EDITOR
                    UnityEngine.Profiling.Profiler.BeginSample($"Singleton_{typeof(T).Name}");
                    GameObject obj = new GameObject(typeof(T).Name);
                    obj.hideFlags = HideFlags.DontSave;
                    _instance = (T)obj.AddComponent(typeof(T));
                    UnityEngine.Profiling.Profiler.EndSample();
#else
                    GameObject obj = new GameObject();
                    obj.hideFlags = HideFlags.HideAndDontSave;
                    _instance = (T)obj.AddComponent(typeof(T));
#endif
                }
            }
            return _instance;
        }
    }

    public virtual void Awake()
    {
        if (transform.parent == null)
            DontDestroyOnLoad(this.gameObject);
        if (_instance == null)
        {
            _instance = this as T;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public virtual void Dispose()
    {
        DestroyImmediate(gameObject);
    }

    public virtual void OnApplicationQuit()
    {
        Destroy(gameObject);
    }

    public virtual void OnDestroy()
    {
        _instance = null;
    }

}